package com.jasonjan.jiance.global

import android.content.Context
import android.content.pm.ApplicationInfo
import android.util.Log

/**
 * Created by jasonjan on 2018/3/13.
 */

/**
 * 打印堆栈信息，扩展Throwable的一个类
 */
fun Throwable.debugPrint(){

    if (!LogUtils.APP_IS_DEBUG){
        return
    }
    val stack = this.stackTrace[1]
    val file = stack.fileName
    val method = stack.methodName
    val line = stack.lineNumber
    LogUtils.d("DebugPrint**********","file**********"+file+",method**********<"+method+">,line**********("+line.toString()+")\n")
}


object LogUtils {

    //是否是debug模式
    var APP_IS_DEBUG = false
    //设为false关闭日志
    val LOG_ENABLE = APP_IS_DEBUG
    fun init(context: Context) {
        APP_IS_DEBUG = isApkDebugable(context)
    }

    /**
     * 但是当我们没在AndroidManifest.xml中设置其debug属性时:
     * 使用Eclipse运行这种方式打包时其debug属性为true,使用Eclipse导出这种方式打包时其debug属性为法false.
     * 在使用ant打包时，其值就取决于ant的打包参数是release还是debug.
     * 因此在AndroidMainifest.xml中最好不设置android:debuggable属性置，而是由打包方式来决定其值.
     */
    fun isApkDebugable(context: Context): Boolean {
        try {
            val info = context.applicationInfo
            return info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
        } catch (e: Exception) {
        }
        return false
    }

    fun i(tag: String, msg: String) {
        if (LOG_ENABLE) {
            Log.i(tag, msg)
        }
    }

    fun v(tag: String, msg: String) {
        if (LOG_ENABLE) {
            Log.v(tag, msg)
        }
    }

    fun d(tag: String, msg: String) {
        if (LOG_ENABLE) {
            Log.d(tag, msg)
        }
    }

    fun w(tag: String, msg: String) {
        if (LOG_ENABLE) {
            Log.w(tag, msg)
        }
    }

    fun e(tag: String, msg: String) {
        if (LOG_ENABLE) {
            Log.e(tag, msg)
        }
    }

    fun d_debugprint(tag:String,msg:String){
        LogUtils.d(tag,msg)
        Throwable().debugPrint()
    }

}
